package net.wang.concurrency.test.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedExample2 {


    /**
     * synchronized 修饰一个类
     */
    public static void test1() {
        synchronized (SynchronizedExample2.class) {
            for (int i = 0; i < 10; i++) {
                log.info("test===1 {}", i);
            }
        }
    }


    /**
     * synchronized 修饰一个静态方法
     */
    public static synchronized void test2() {
        for (int i = 0; i < 10; i++) {
            log.info("test===2 {}", i);
        }
    }

    public static void safeTest() {
        SynchronizedExample2 example1 = new SynchronizedExample2();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> example1.test1());
        executorService.execute(() -> example1.test2());
    }


    /**
     * 这种方式依然是同步的，类似于锁的是类，类存在于主内存中，是安全的
     */
    public static void alsoSafeTest() {
        SynchronizedExample2 example1 = new SynchronizedExample2();
        SynchronizedExample2 example2 = new SynchronizedExample2();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> example1.test1());
        executorService.execute(() -> example2.test2());
    }

    public static void main(String[] args) {
        //safeTest();
        alsoSafeTest();
    }
}
